<?php
/**
 * DolphinGTK - phpGtk framework
 *
 * @package    DolphinGTK
 * @author     Askarov Ruslan
 * @copyright  Askarov Ruslan (c) 2010.
 * @link       http://groups.google.com/group/dolphingtk
 * @license    http://www.opensource.org/licenses/gpl-license.php GPL
 * @version    0.1
 * @since      PHP v.: 5.2.1
 * @subpackage desktop
 * @category   library
 * @filesource
 */


final class Connector
{
  private $connID;
  public $timeout = 5;
  public $errorNumber, $errorMessage;


  public function connect( $host, $port )
  {
    if( empty($host) ) {
      return 'enter_host_name';
    }

    if( !is_numeric($port) ) {
      return 'port_not_numeric';
    }

    if( $this->connID ) {
      return 'connected';
    }

    $this->connID = @fsockopen( 
      $host, $port, $this->errorNumber, $this->errorMessage, $this->timeout
    );

    if( !$this->connID ) {
      return $this->errorMessage;
    } else {
      return true;
    }
  }




  public function disconnect()
  {
    if( $this->connID ) {
      fclose($this->connID);
    }
    else {
      return 'not_connected';
    }
  }




  public function lines()
  {
    $i = 0;

    while ( ($lines[] = $this->get() ) != "."  )
    {
      if( $lines[$i] == '.' or $lines[$i] == 'error' ) {
        break;
      }
      $i++;
    }

    $cnt = (count($lines)-1);
    $lines = array_slice($lines,0, $cnt);

    return implode("\n",$lines);
  }




  public function get( $size = 1024 )
  {
    if( !feof($this->connID) )
    {
      stream_set_timeout($this->connID, $this->timeout);

      $get = fgets( $this->connID, $size );

      $socet_status = stream_get_meta_data($this->connID);

      if( $socet_status['timed_out'] ) {
        return 'socet_timeout';
      }

      if ( $socet_status['eof'] ) {
        return 'connection_aborted';
      }

      $get = self::removeLineBreaks( $get );
      $get = trim( $get );
    }

    return $get;
  }




  private function removeLineBreaks( $string = false )
  {
    return strtr( $string, "\n", "  " );
  }




  public function set( $command = false )
  {
    if( !$command ) return false;

    stream_set_timeout($this->connID, $this->timeout);

    $write = fwrite($this->connID, self::removeLineBreaks($command)."\n");

    if( !$write ) {
      return false;
    } else {
      return true;
    }
  }

}
?>
